package com.up4years.dataapi.service.support;

import java.io.IOException;
import java.util.Date;
import java.util.Random;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.up4years.dataapi.dao.support.MobileMessageMapper;
import com.up4years.dataapi.entity.SMSTextMessage;
import com.up4years.utils.CommonUtil;
import com.up4years.utils.DateUtil;
import com.up4years.utils.EncryptUtil;

/**
 * 用户短信接口
 * @author Administrator
 *
 */
@Service
public class SMSService {
	
	Logger logger =Logger.getLogger(SMSService.class);
	@Autowired
	private MobileMessageMapper mobileMessageMapper;
	private  final String IDENTIFY_CODE_URI_TEMPLATE = "https://api.ucpaas.com/{SoftVersion}/Accounts/{accountSid}/{function}/{operation}?sig={SigParameter}";
	/**有效期**/
	private  final int VALID_MINUTE= 3;
 


	public SMSTextMessage getById(long id){
		return this.mobileMessageMapper.get(id);
	}
	public SMSTextMessage insert(SMSTextMessage textMessage){
		 mobileMessageMapper.create(textMessage);
		 return textMessage;
 	}
	/**
	 * 一分钟内发过时禁止重发
	 * @param phone
	 * @return
	 */
	public boolean sendAllowed(String phone){
		long count = this.mobileMessageMapper.getValidTextMessage(phone, new Date());
 		return count ==0;
	}
	/**
	 * 给用户发送验证码
	 * @param toNum 用户手机号码
	 * @throws JSONException
	 * @throws HttpException
	 * @throws IOException
	 * return TextMessage
	 */
	@SuppressWarnings("deprecation")
	public SMSTextMessage sendIdentifyMessage(String toNum) throws JSONException, HttpException, IOException {
		String timestamp = DateUtil.dateFormat(new Date(), "yyyyMMddHHmmss");
		String sig = getSigParameter(timestamp);
		String authrization = getAuthrization(timestamp);
		String uri = IDENTIFY_CODE_URI_TEMPLATE.replace("{SoftVersion}", "2014-06-30")
				.replace("{accountSid}", CommonUtil.getUCPASS_ACCOUNT_ID())
				.replace("{function}", "Messages")
				.replace("{operation}", "templateSMS")
				.replace("{SigParameter}", sig);
		String code = new Random().nextInt(10000)+"";
 		String param= code+","+VALID_MINUTE;
		JSONObject json = this.getTemplateBody(CommonUtil.getUCPASS_REGISTER_CODE_TEMPLATE_ID(), param, toNum);
 		HttpClient client = new HttpClient();		
			PostMethod method= new PostMethod();
			method.setURI(new URI(uri));
			method.addRequestHeader("Accept", "application/json");
			method.addRequestHeader("Content-Type","application/json;charset=utf-8;");
			method.addRequestHeader("Authorization", authrization);
			method.setRequestEntity(new StringRequestEntity(json.toString()));
		int statusCode = client.executeMethod(method);
		String content = CommonUtil.getUCPASS_REGISTER_CODE_TEMPLATE_CONTENT().replace("{1}", code).replace("{2}", VALID_MINUTE+"");
		Date now = new Date();
		Date expire = new Date(now.getTime());
		expire.setMinutes(expire.getMinutes()+VALID_MINUTE);
		SMSTextMessage textMessage = new SMSTextMessage();
			textMessage.setMobile(toNum);
			textMessage.setCode(code);
			textMessage.setContent(content);
			textMessage.setChannel("云之讯");
	 		textMessage.setCreate_time(now);
	 		textMessage.setReturn_time(now);
	 		textMessage.setExpire_time(expire);
	 		textMessage.setIs_verified(0);
	 		textMessage.setReturn_code(statusCode);
  		
		return this.insert(textMessage);
  	}
	private JSONObject getTemplateBody(String templateId,String param,String toNum) throws JSONException{
		JSONObject json = new JSONObject();
		JSONObject templateSMS = new JSONObject();
		templateSMS.put("appId", CommonUtil.getUCPASS_UCPASS_APP_ID());
		templateSMS.put("templateId", templateId);
		templateSMS.put("param", param);
		templateSMS.put("to", toNum);
		json.put("templateSMS", templateSMS);
		return json;
	} 
	private String getSigParameter(String timestamp) {
		return EncryptUtil.MD5Encode(CommonUtil.getUCPASS_ACCOUNT_ID()  + CommonUtil.getUCPASS_ACCOUNT_TOKEN() + timestamp);
	}

	private String getAuthrization(String timestamp) {
		String s = CommonUtil.getUCPASS_ACCOUNT_ID() + ":" + timestamp;
		return Base64.encodeBase64String(s.getBytes());
	}
}
